package com.weishuang.monitor.leader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weishuang.monitor.leader.entity.SysUserRole;
import com.weishuang.monitor.leader.mapper.SysUserRoleMapper;
import com.weishuang.monitor.leader.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishuang.monitor.leader.service.SysCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author weishuang
 * @since 2021-03-23
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Autowired
    private SysCacheService sysCacheService;

    /**
     * 用户授权角色
     * @param roleIds
     * @param userId
     */
    @Override
    public void allotRoleForUser(String[] roleIds, String userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        baseMapper.delete(queryWrapper);

        if (roleIds != null && roleIds.length > 0) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            for (String roleId : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                sysUserRoleList.add(sysUserRole);
            }
            this.saveBatch(sysUserRoleList);
        }

        sysCacheService.clearSysMenuPermissionByUserCode(userId);
    }
}
